package tgc.edu.library.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.library.custom.CommonController;
import tgc.edu.library.entity.BookType;
import tgc.edu.library.web.form.BookTypeForm;

@Controller
@RequestMapping(value="/bookType")
public class BookTypeController extends CommonController<BookType, Integer, BookTypeForm> {

	@Override
	public Specification<BookType> buildSpec(BookTypeForm form) {
		Specification<BookType> specification=new Specification<BookType>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<BookType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String search = form.getSearch();
				if(StringUtils.hasText(search)) {
					Predicate name = cb.like(root.get("type"), "%"+search+"%");
					Predicate code = cb.like(root.get("code"), "%"+search+"%");
					Predicate or = cb.or(name, code);
					rules.add(or);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return specification;
	}
	
}
